import 'dart:convert';
import 'dart:io';

import 'package:dio/dio.dart';
import 'package:dio/io.dart';
import 'package:flutter/foundation.dart';

/// transformer
class ResponseTransformer extends BackgroundTransformer {
  @override
  set jsonDecodeCallback(JsonDecodeCallback _) {
    super.jsonDecodeCallback = _parseJson;
  }

  /// compute函数要求第一个参数是静态的函数
  static Map<String, dynamic> _parseAndDecode(String response) {
    return jsonDecode(response) as Map<String, dynamic>;
  }

  Future<Map<String, dynamic>> _parseJson(String text) {
    return compute(_parseAndDecode, text);
  }
}

/// 原生 adapter
class NativeHttpAdapter extends IOHttpClientAdapter {
  NativeHttpAdapter()
      : super(createHttpClient: () {
          final client =
              HttpClient(context: SecurityContext(withTrustedRoots: false));
          // You can test the intermediate / root cert here. We just ignore it.
          client.badCertificateCallback = (cert, host, port) => true;
          return client;
        });
}

// /// Web adapter  必须配置好web环境配置 不然启动不了
// class WebHttpClientAdapter extends BrowserHttpClientAdapter {
//   WebHttpClientAdapter({final bool withCredentials = false})
//       : super(withCredentials: withCredentials);
// }
